package com.raysdata.smartcity.web.sys;

import com.alibaba.fastjson.JSON;
import com.raysdata.smartcity.HelperClazz;
import com.raysdata.smartcity.Key;
import com.raysdata.smartcity.dao.sys.MenuDao;
import com.raysdata.smartcity.dto.Menu;
import com.raysdata.smartcity.dto.Role;
import com.raysdata.smartcity.dto.User;
import com.raysdata.smartcity.web.BaseController;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by liux on 2016/10/14.
 * 角色信息controller
 */
@Controller
@RequestMapping(value = "/role")
public class RoleController extends BaseController {

    @Autowired
    public MenuDao menuDao;
    /**
     * 角色列表页跳转
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/toRoleIndex", method = RequestMethod.GET)
    public String toRoleIndex(Model model, HttpServletRequest request, HttpServletResponse response) {
        return "smartcity/roleManage/roleList";
    }

    /**
     * 角色列表页
     * @param request
     * @param response
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    @RequestMapping(value = "/getRoleList")
    public void getRoleList(HttpServletRequest request,HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
        Map filter= WebUtils.getParametersStartingWith(request, "query_");
        Role role=new Role();
        BeanUtils.populate(role, filter);
        List<Role> roles = new ArrayList<Role>();
        int page = HelperClazz.getCurrentPage(request);
        int count = HelperClazz.getPageSize(request);
        roles = roleDao.queryRoles(page,count,role);
        HelperClazz.renderJson(response,HelperClazz.toJSON4Page(roles));
    }

    /**
     * 角色新页跳转
     * @param modele
     * @param request
     * @return
     */
    @RequestMapping(value = "/toRoleAdd")
    public String toRoleAdd(Model modele,HttpServletRequest request){
        return "smartcity/roleManage/roleAdd";
    }

    /**
     * 角色修改页跳转
     * @param modele
     * @param request
     * @return
     */
    @RequestMapping(value = "/toRoleUpdate")
    public String toRoleUpdate(Model modele,HttpServletRequest request){
        String id=request.getParameter("role_id");

        Role role=this.roleDao.getRoleById(id);

        request.setAttribute("role",role);
        return "smartcity/roleManage/roleUpdate";
    }

    /**
     * 保存角色
     * @param role
     * @param request
     * @param response
     */
    @RequestMapping(value = "/doSave")
    public void addSave(@ModelAttribute("role")Role role, HttpServletRequest request, HttpServletResponse response){
        int result=-1;
        String type="";
        String content="";
        User user=(User)request.getSession().getAttribute("LoginUser");

        if(HelperClazz.isEmpty(role.getRole_id())) {
            result=roleDao.addRole(role);
            type=Key.LOG_ADD;
            content="新增角色："+role.getName();
        }else{
            result=roleDao.updRole(role);
            type=Key.LOG_UPDATE;
            content="修改角色："+role.getName();
        }

        if(result==0){
            logDao.saveLog(request,content,type,user,role.getName(),Key.LOG_SUCCESS);
            HelperClazz.renderJson(response, "{\"success\":true,\"msg\":\"角色保存成功！\"}");
        }else{
            logDao.saveLog(request,content,type,user,role.getName(),Key.LOG_ERROR);
            HelperClazz.renderJson(response, "{\"success\":true,\"msg\":\"角色保存失败！\"}");
        }

    }

    /**
     * 删除角色
     * @param request
     * @param response
     */
    @RequestMapping(value = "/deleteRole")
    public void deleteRole(HttpServletRequest request,HttpServletResponse response){
        String id=request.getParameter("role_id");
        String content="删除角色：";
        String type=Key.LOG_DELETE;
        // 获取当前用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("LoginUser");
        Role role=roleDao.getRoleById(id);

        try {
            //校验角色是否被使用
            List<Map<String,Object>> list=this.roleDao.queryUserByRoleId(id);
            if(list.size()>0){
                HelperClazz.renderJson(response, "{\"success\":false,\"msg\":\"角色已被用户使用，无法删除！\"}");
            }else{
                this.roleDao.delRoleById(id);
                logDao.saveLog(request,content+role.getName(),type,user,role.getName(), Key.LOG_SUCCESS);
                HelperClazz.renderJson(response, "{\"success\":true,\"msg\":\"角色删除成功！\"}");
            }

        }catch(Exception e) {
            e.printStackTrace();
            logDao.saveLog(request,content+role.getName(),type,user,role.getName(), Key.LOG_ERROR);
            HelperClazz.renderJson(response, "{\"success\":false,\"msg\":\"角色删除失败！\"}");
        }
    }

    /**
     * 校验角色是否存在
     * @param request
     * @param response
     */
    @RequestMapping(value = "/checkName")
    public void checkName(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        String role_id = request.getParameter("role_id");

        boolean bl;
        if(HelperClazz.isEmpty(role_id)){
            bl =  rzBaseDao.chkIsExist("ss_role", "name", name)==0;
        }else{
            String nameDb=roleDao.getRoleById(role_id).getName();
            if(nameDb.equals(name)){
                bl=true;
            }else{
                bl = rzBaseDao.chkIsExist("ss_role", "name", name)==0;
            }
        }
        HelperClazz.renderJson(response, "{ \"valid\": " + bl + " }");
    }

    @RequestMapping(value = "/selectMenus")
    public void selectRoles(HttpServletRequest request, HttpServletResponse response) {
        String role_id=request.getParameter("role_id");

        //查询所有菜单
        List<Menu> menus = new ArrayList<Menu>();
        menus = menuDao.queryAllMenus();
        //查询已配置菜单
        List<Map<String,Object>> list= this.roleDao.queryMenuByRoleId(role_id);

        HelperClazz.renderJson(response,"{\"menuAll\":"+ JSON.toJSONString(menus)+",\"roleMenus\":"+JSON.toJSONString(list)+"}");
    }

    @RequestMapping(value = "/configMenus")
    public void configMenus(HttpServletRequest request,HttpServletResponse response){
        String role_id=request.getParameter("role_id");
        String ids=request.getParameter("menu_id");
        try {
            //清空菜单
            this.roleDao.delRoleMenus(role_id);
            //配置新菜单
            String[] idArray=ids.split(",");
            for(int i=0;i<idArray.length;i++){
                String menu_id=idArray[i];
                this.roleDao.configMenus(role_id,menu_id);
            }
            HelperClazz.renderJson(response, "{\"success\":true,\"msg\":\"权限配置成功！\"}");

        }catch(Exception e) {
            e.printStackTrace();
            HelperClazz.renderJson(response, "{\"success\":false,\"msg\":\"权限配置失败！\"}");
        }
    }

}
